const express = require('express');
const session = require('express-session');
const md5 = require('md5');

const userModel = require('../db/models/userModel');

const router = express.Router();

router.use(session({
    secret:'0825',
    saveUninitialized:false,
    resave:false,
    cookie:{
        httpOnly:true,
        maxAge:1000*60*60*24
    }
}))

router.get('/login',(req,res)=>{
    res.render('./login.ejs');
})

router.post('/login',(req,res)=>{
    let {username,pwd} = req.body;

    userModel.find({username,pwd:md5(pwd)},(err,data)=>{
        if(data.length){
            req.session.username = username;
            res.json({msg:"登录成功",code:200})
            // res.redirect('/list');
        }else{
            res.json({msg:'用户名或密码错误',code:201});
            // res.redirect('/login');
        }
    });

})

router.get('/register',(req,res)=>{
    res.render('./register.ejs');
})

router.post('/register',(req,res)=>{
    let {username,pwd} = req.body;

    // 判断是否已有账号
    userModel.find({username},(err,data)=>{
        if(data.length){
            res.json({
                msg:"用户名已被占用",
                code:201
            })
        }else{
            userModel.insertMany([{username,pwd:md5(pwd)}],(err,data)=>{
                if(err) throw err;
                res.json({
                    msg:"注册成功",
                    code:200
                })
            })
        }
    }); 
})

router.get('/logout',(req,res)=>{
    
    req.session.destroy(()=>{
        res.render('logout');
    });

})


module.exports = router;